package cn.jieruoda.eb.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import cn.dev33.satoken.util.SaResult;
import cn.jieruoda.eb.system.domain.entity.SystemRole;
import cn.jieruoda.eb.system.domain.entity.SystemRoleMenu;
import cn.jieruoda.eb.system.domain.repository.SystemRoleMenuRepository;
import cn.jieruoda.eb.system.domain.repository.SystemRoleRepository;
import cn.jieruoda.eb.system.dto.RoleMenusDTO;
import lombok.RequiredArgsConstructor;

/**
 * 角色管理控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/role")
public class RoleController {

    final SystemRoleRepository systemRoleRepository;
    final SystemRoleMenuRepository systemRoleMenuRepository;

    @GetMapping("list")
    public SaResult list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        // StpUtil.checkPermission("sys:role:list");
        return SaResult.data(systemRoleRepository.findAll(PageRequest.of(page, size)));
    }

    @GetMapping("{id}")
    public SaResult getRole(@PathVariable Integer id) {
        // StpUtil.checkPermission("sys:role:info");
        SystemRole role = systemRoleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("角色不存在"));

        // 查询角色关联的菜单ID列表
        List<SystemRoleMenu> roleMenus = systemRoleMenuRepository.findByRid(id);
        List<Integer> menuIds = new ArrayList<>();
        for (SystemRoleMenu rm : roleMenus) {
            menuIds.add(rm.getMenuId());
        }

        RoleMenusDTO dto = new RoleMenusDTO();
        dto.setRole(role);
        dto.setMenuIds(menuIds);

        return SaResult.data(dto);
    }

    @PostMapping("create")
    @Transactional
    public SaResult create(@RequestBody RoleMenusDTO roleMenus) {
        // StpUtil.checkPermission("sys:role:create");
        SystemRole role = roleMenus.getRole();
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        role.setStatus(1);

        // 保存角色
        SystemRole savedRole = systemRoleRepository.save(role);

        // 保存角色菜单关联
        saveRoleMenus(savedRole.getId(), roleMenus.getMenuIds());

        return SaResult.ok("创建成功");
    }

    @PutMapping("{id}")
    @Transactional
    public SaResult update(@PathVariable Integer id, @RequestBody RoleMenusDTO roleMenus) {
        // StpUtil.checkPermission("sys:role:update");
        SystemRole role = roleMenus.getRole();
        SystemRole existingRole = systemRoleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("角色不存在"));

        role.setId(id);
        role.setCreateTime(existingRole.getCreateTime());
        role.setUpdateTime(new Date());
        role.setStatus(existingRole.getStatus());

        // 更新角色
        systemRoleRepository.save(role);

        // 更新角色菜单关联
        systemRoleMenuRepository.deleteByRid(id);
        saveRoleMenus(id, roleMenus.getMenuIds());

        return SaResult.ok("更新成功");
    }

    @DeleteMapping("{id}")
    @Transactional
    public SaResult delete(@PathVariable Integer id) {
        // StpUtil.checkPermission("sys:role:delete");
        if (id == 1) {
            return SaResult.error("超级管理员角色不能删除");
        }

        // 删除角色菜单关联
        systemRoleMenuRepository.deleteByRid(id);

        // 删除角色
        systemRoleRepository.deleteById(id);

        return SaResult.ok("删除成功");
    }

    private void saveRoleMenus(Integer roleId, List<Integer> menuIds) {
        if (menuIds != null && !menuIds.isEmpty()) {
            for (Integer menuId : menuIds) {
                SystemRoleMenu roleMenu = new SystemRoleMenu();
                roleMenu.setRid(roleId);
                roleMenu.setMenuId(menuId);
                systemRoleMenuRepository.save(roleMenu);
            }
        }
    }
}